<template>
  <div class="student-course-wrap">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-fa fa-edit"></i> 选课管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container">
      <!-- 统计卡片区域 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-data-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-title">选课总数</div>
              <div class="stat-value">{{ tableData.length }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon green">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-title">平均分数</div>
              <div class="stat-value">{{ getAverageScore() }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon blue">
              <i class="el-icon-trophy"></i>
            </div>
            <div class="stat-info">
              <div class="stat-title">优秀率</div>
              <div class="stat-value">{{ getExcellentRate() }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon purple">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-info">
              <div class="stat-title">不及格率</div>
              <div class="stat-value">{{ getFailRate() }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 操作区域 -->
      <div class="action-card">
        <el-row :gutter="24" type="flex" justify="space-between" align="middle">
          <el-col :span="6">
            <el-button @click="create" type="primary" icon="el-icon-plus" size="medium" class="create-btn">添加选课</el-button>
          </el-col>
          <el-col :span="14">
            <el-row :gutter="15">
              <el-col :span="8">
                <el-input
                  v-model="queryForm.courseName"
                  placeholder="请输入课程名称"
                  prefix-icon="el-icon-reading"
                  clearable
                  @keyup.enter.native="query"
                  class="search-input"
                />
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="queryForm.majorName"
                  placeholder="请输入专业名称"
                  prefix-icon="el-icon-office-building"
                  clearable
                  @keyup.enter.native="query"
                  class="search-input"
                />
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="queryForm.className"
                  placeholder="请输入班级名称"
                  prefix-icon="el-icon-school"
                  clearable
                  @keyup.enter.native="query"
                  class="search-input"
                />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="4" style="text-align: right;">
            <el-button @click="query" type="primary" icon="el-icon-search" class="search-btn">搜索</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 权限控制区域 -->
      <div class="permission-card">
        <div class="permission-title">
          <i class="el-icon-setting"></i>
          <span>系统控制</span>
        </div>
        <div class="permission-switches">
          <div class="switch-item">
            <el-switch
              v-model="optionForm.allowSelect"
              @change="updateAllowSelect"
              active-text="允许选课"
              inactive-text="禁止选课"
              active-color="#67C23A"
              inactive-color="#F56C6C"
            >
            </el-switch>
          </div>
          <div class="switch-item">
            <el-switch
              v-model="optionForm.allowGrade"
              @change="updateAllowGrade"
              active-text="允许打分"
              inactive-text="禁止打分"
              active-color="#67C23A"
              inactive-color="#F56C6C"
            >
            </el-switch>
          </div>
        </div>
      </div>

      <!-- 选课列表 -->
      <div class="course-list">
        <div v-for="(item, index) in tableData" :key="index" class="course-item">
          <div class="course-item-left">
            <div class="course-info">
              <div class="course-name">
                <span class="name">{{ item.courseName }}</span>
                <el-tag 
                  size="small" 
                  :type="getScoreTagType(item.score)"
                  effect="dark"
                >{{ item.score || '未评分' }}</el-tag>
              </div>
              <div class="student-info">
                <span class="label"><i class="el-icon-user"></i> 学生：</span>
                <span class="value">{{ item.studentName }}</span>
                <span class="divider">|</span>
                <span class="label"><i class="el-icon-school"></i> 班级：</span>
                <span class="value">{{ item.className }}</span>
              </div>
              <div class="score-info">
                <div class="score-item">
                  <span class="label">日常分：</span>
                  <span class="value" :class="getScoreClass(item.dailyScore)">
                    {{ item.dailyScore || '未评分' }}
                  </span>
                </div>
                <div class="score-item">
                  <span class="label">期末分：</span>
                  <span class="value" :class="getScoreClass(item.examScore)">
                    {{ item.examScore || '未评分' }}
                  </span>
                </div>
                <div class="score-item">
                  <span class="label">总分：</span>
                  <span class="value" :class="getScoreClass(item.score)">
                    {{ item.score || '未评分' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="course-item-right">
            <el-button
              @click="edit(item.id)"
              type="primary"
              icon="el-icon-edit"
              size="small"
            >编辑</el-button>
            <el-button
              @click="deleteItem(item.id)"
              type="danger"
              icon="el-icon-delete"
              size="small"
            >删除</el-button>
          </div>
        </div>

        <div class="pagination-container">
          <el-pagination
            @current-change="getPage"
            :current-page.sync="pageIndex"
            :page-size="pageSize"
            :total="pageSize * pageCount"
            background
            layout="total, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
        :visible.sync="editing"
        :title="entityForm.id === -1 ? '新增选课' : '编辑选课'"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        custom-class="custom-dialog"
      >
        <el-form
          :model="entityForm"
          ref="form"
          label-width="80px"
          class="custom-form"
        >
          <el-form-item label="学生" prop="studentId">
            <el-select
              :disabled="entityForm.id !== -1"
              v-model="entityForm.studentId"
              placeholder="请选择学生"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in students"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课程" prop="courseId">
            <el-select
              :disabled="entityForm.id !== -1"
              v-model="entityForm.courseId"
              placeholder="请选择课程"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in courses"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="日常得分" prop="dailyScore">
            <el-input-number 
              v-model="entityForm.dailyScore" 
              :min="0" 
              :max="100"
              :step="1"
              style="width: 100%;"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="考试得分" prop="examScore">
            <el-input-number 
              v-model="entityForm.examScore" 
              :min="0" 
              :max="100"
              :step="1"
              style="width: 100%;"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="总分" prop="score">
            <el-input-number 
              v-model="entityForm.score" 
              :min="0" 
              :max="100"
              :step="1"
              style="width: 100%;"
            ></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editing = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as api from "../../api/admin/studentCourse";
import * as CourseApi from "../../api/admin/course";
import * as StudentApi from "../../api/admin/student";
import * as OptionApi from "../../api/option";

export default {
  name: "AdminStudentCourse",
  data() {
    return {
      queryForm: {
        className: "",
        courseName: "",
        studentName: ""
      },
      optionForm: {
        allowSelect: true,
        allowGrade: true
      },
      entityForm: {},
      tableData: [],
      pageSize: api.pageSize,
      pageCount: 1,
      pageIndex: 1,
      editing: false,
      courses: [],
      students: []
    };
  },
  methods: {
    query() {
      api
        .getPageCount(
          this.queryForm.className,
          this.queryForm.courseName,
          this.queryForm.studentName
        )
        .then(res => {
          this.pageCount = res;
          this.pageIndex = 1;
          this.getPage(1);
        });
    },
    getPage(pageIndex) {
      api
        .getPage(
          pageIndex,
          this.queryForm.className,
          this.queryForm.courseName,
          this.queryForm.studentName
        )
        .then(res => {
          this.tableData = res;
        });
    },
    create() {
      this.entityForm = {
        id: -1,
        studentId: null,
        courseId: null,
        dailyScore: null,
        examScore: null,
        score: null
      };
      this.editing = true;
    },
    edit(id) {
      api.get(id).then(res => {
        this.entityForm = res;
        this.editing = true;
      });
    },
    save() {
      if (this.entityForm.id === -1) {
        api.create(this.entityForm).then(() => {
          this.finishSave();
        });
      } else {
        api.update(this.entityForm).then(() => {
          this.finishSave();
        });
      }
    },
    finishSave() {
      this.$message.success("成功");
      this.getPage(this.pageIndex);
      this.editing = false;
    },
    deleteItem(id) {
      api.deleteItem(id).then(() => {
        this.$message.success("删除成功");
        this.getPage(this.pageIndex);
      });
    },
    getCoursesAndStudents() {
      CourseApi.listName().then(res => {
        this.courses = res;
      });
      StudentApi.listName().then(res => {
        this.students = res;
      });
    },
    getSelectAndGradeStatus() {
      OptionApi.getAllowStudentSelect().then(res => {
        this.optionForm.allowSelect = res;
      });
      OptionApi.getAllowTeacherGrade().then(res => {
        this.optionForm.allowGrade = res;
      });
    },
    updateAllowSelect(val) {
      OptionApi.setAllowStudentSelect(val);
    },
    updateAllowGrade(val) {
      OptionApi.setAllowTeacherGrade(val);
    },
    getScoreTagType(score) {
      if (!score) return 'info';
      if (score >= 90) return 'success';
      if (score >= 60) return 'warning';
      return 'danger';
    },
    getScoreClass(score) {
      if (!score) return 'score-none';
      if (score >= 90) return 'score-excellent';
      if (score >= 60) return 'score-pass';
      return 'score-fail';
    },
    getAverageScore() {
      if (this.tableData.length === 0) return '0';
      const validScores = this.tableData.filter(item => item.score);
      if (validScores.length === 0) return '0';
      const total = validScores.reduce((sum, item) => sum + item.score, 0);
      return (total / validScores.length).toFixed(1);
    },
    getExcellentRate() {
      if (this.tableData.length === 0) return '0%';
      const validScores = this.tableData.filter(item => item.score);
      if (validScores.length === 0) return '0%';
      const excellent = validScores.filter(item => item.score >= 90).length;
      return Math.round((excellent / validScores.length) * 100) + '%';
    },
    getFailRate() {
      if (this.tableData.length === 0) return '0%';
      const validScores = this.tableData.filter(item => item.score);
      if (validScores.length === 0) return '0%';
      const fail = validScores.filter(item => item.score < 60).length;
      return Math.round((fail / validScores.length) * 100) + '%';
    }
  },
  created() {
    this.query();
    this.getCoursesAndStudents();
    this.getSelectAndGradeStatus();
  }
};
</script>

<style scoped>
.student-course-wrap {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 100px);
}

.crumbs {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 统计卡片样式 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;

  i {
    font-size: 24px;
    color: #fff;
  }

  &.green {
    background: #67C23A;
  }

  &.blue {
    background: #409EFF;
  }

  &.purple {
    background: #F56C6C;
  }
}

.stat-info {
  flex: 1;

  .stat-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
}

/* 操作区域样式 */
.action-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 搜索框样式 */
.search-input {
  ::v-deep .el-input__inner {
    border-radius: 4px;
    transition: all 0.3s;
    
    &:focus {
      border-color: #409EFF;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }
}

.search-btn {
  padding: 12px 20px;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }
}

/* 创建按钮样式 */
.create-btn {
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }
}

/* 选课列表样式 */
.course-list {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.course-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  transition: all 0.3s;

  &:hover {
    background: #f8f9fa;
    transform: translateX(5px);
  }

  &:last-child {
    border-bottom: none;
  }
}

.course-item-left {
  flex: 1;
}

.course-name {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .name {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-right: 10px;
  }
}

.student-info {
  color: #606266;
  margin-bottom: 10px;

  .label {
    color: #909399;
    margin-right: 5px;
  }

  .divider {
    margin: 0 10px;
    color: #dcdfe6;
  }

  i {
    margin-right: 5px;
  }
}

.score-info {
  display: flex;
  gap: 20px;
}

.score-item {
  .label {
    color: #909399;
  }

  .value {
    font-weight: 500;
    margin-left: 5px;

    &.score-excellent {
      color: #67C23A;
    }

    &.score-pass {
      color: #E6A23C;
    }

    &.score-fail {
      color: #F56C6C;
    }

    &.score-none {
      color: #909399;
    }
  }
}

.course-item-right {
  display: flex;
  gap: 10px;

  .el-button {
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

/* 分页器样式 */
.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  text-align: right;
}

/* 弹窗样式 */
.custom-dialog {
  ::v-deep .el-dialog {
    border-radius: 8px;
    overflow: hidden;
  }
  
  ::v-deep .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    margin: 0;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  ::v-deep .el-dialog__body {
    padding: 24px;
  }
  
  ::v-deep .el-dialog__footer {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
    background: #f8f9fa;
  }
}

.custom-form {
  ::v-deep .el-form-item__label {
    font-weight: 500;
    color: #606266;
  }
  
  ::v-deep .el-input__inner {
    border-radius: 4px;
    transition: all 0.3s;
    
    &:focus {
      border-color: #409EFF;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }
}

/* 权限控制区域样式 */
.permission-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.permission-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  color: #606266;
  font-weight: 500;
  
  i {
    font-size: 18px;
    margin-right: 8px;
    color: #409EFF;
  }
  
  span {
    font-size: 16px;
  }
}

.permission-switches {
  display: flex;
  gap: 40px;

  .switch-item {
    display: flex;
    align-items: center;
    
    ::v-deep .el-switch__label {
      color: #606266;
      font-weight: 500;
    }
    
    ::v-deep .el-switch {
      margin-right: 8px;
    }
  }
}
</style>
